<template>
  <el-dialog
    :visible="visible"
    :before-close="handleClose"
    :close="handleClose"
    :show-close="!showMobilePage"
    :class="{'global-mobile-dialog':showMobilePage}"
    class="small-common-dialog-size operator-dialog"
  >
    <Title title="运营人员设置" style="margin-bottom:24px" />
    <el-form
      ref="opForm"
      :rules="rules"
      :model="formData"
      class="form"
      size="small">
      <el-form-item prop="accountOperation">
        <el-select
          v-loadmore="LoadMoreList"
          v-model="formData.accountOperation"
          :multiple="true"
          :multiple-limit="5"
          :filter-method="filterData"
          name="accountOperation"
          class="operator-select"
          filterable
          clearable
          style="width: 100%;"
          placeholder="请选择运营人员"
          @focus="getUser(1, '')"
          @change="selectUser"
          @clear="getUser"
        >
          <el-option
            v-for="(select, index) in defaultUserList"
            :key="select.id + 'id' + index"
            :label="select.userName"
            :value="select.id" />
          <el-option
            v-for="(select, index) in selectUserData"
            :key="select.id + 'select' + index"
            :label="select.userName"
            :value="select.id"
            style="display:none;"
          />
          <el-option
            v-for="(select, index) in userList.items"
            :key="index"
            :label="select.userName"
            :value="select.id" />
          <div v-if="userLoading" class="loading-container"><i class="el-icon-loading"/></div>
        </el-select>
      </el-form-item>
    </el-form>
    <div style="margin-bottom: 16px;">注意：微博数据出现未达标等情况系统会对运营人员发送飞书通知；无效链接将无法正常采集。</div>
    <div class="center">
      <el-button
        :disabled="loading"
        :loading="loading"
        type="primary"
        size="small"
        @click="handleSubmit"
      >
        确定
      </el-button>
      <el-button
        type="info"
        size="small"
        class="cancel-btn-style"
        @click="handleClose"
      >取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import Title from '@/components/Title';
import { getList } from '@/api/user';
import { mapState } from 'vuex';
export default {
  components: {
    Title
  },
  props: {
    isCache: {
      type: Boolean,
      default: false
    },
    list: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      formData: {
        accountOperation: []
      },
      userList: {
        items: []
      },
      defaultUserList: [],
      selectUserData: [],
      cacheList: [],
      userLoading: false,
      visible: false,
      loading: false
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    rules() {
      return {
        'status': [{ required: true, message: '请选择状态', trigger: 'blur' }]
      };
    }
  },
  created() {
    this.getUser();
  },
  methods: {
    openDialog() {
      if (this.isCache) {
        const localAccountOperation = sessionStorage.getItem('accountOperation');
        if (!this.list.length && localAccountOperation) {
          // 保留上次修改结果
          this.defaultUserList = JSON.parse(localAccountOperation);
          this.$set(this.formData, 'accountOperation', JSON.parse(localAccountOperation).map(it => it.id));
        }
      }
      if (this.list && this.list.length > 0) {
        // 回填最后设置的值
        this.defaultUserList = this.list;
        this.$set(this.formData, 'accountOperation', this.list.map(it => it.id));
      }
      this.visible = true;
    },
    cancelLoading() {
      setTimeout(() => {
        this.loading = false;
      }, 500);
    },
    filterData(val) {
      if (val) {
        const userName = val;
        this.getUser(1, userName);
      }
    },
    handleClose() {
      this.visible = false;
      this.cancelLoading();
      this.$refs['opForm'].resetFields();
    },
    LoadMoreList() {
      const List = this.userList;
      const currentPage = List.page;
      if (List.items) {
        if (List.items.length < 300 && !this.userLoading) {
          this.getUser(currentPage + 1, '');
        }
      }
    },
    unique(arr) {
      const newArr = [];
      arr.forEach(function(a) {
        const istrue = newArr.every(function(b) {
          return a.id !== b.id;
        });
        istrue ? newArr.push(a) : '';
      });
      return newArr;
    },
    selectUser(value) {
      const userList = this.userList.items;
      this.selectUserData = [];
      if (value && value.length > 0) {
        userList.forEach(i => {
          if (value.includes(i.id)) {
            this.selectUserData.push(i);
          }
        });
        this.selectUserData.filter(i => {
          return value.includes(i.id);
        });
      } else {
        this.selectUserData = [];
      }
      this.cacheList = this.unique([...this.cacheList, ...this.selectUserData, ...this.defaultUserList]).map(it => {
        return {
          id: it.id,
          userName: it.userName,
          avatar: it.avatar
        };
      });
    },
    getUser(page = 1, userName = '') {
      this.userLoading = true;
      const params = {
        userName,
        userStatus: 1,
        dimissionStatus: 1
      };
      getList(page, 15, params).then(({ data }) => {
        this.userLoading = false;
        if (page > 1 && this.userList.items) {
          data.items = this.handeldefaultList(data.items);
          const concatList = this.userList.items.concat(data.items);
          data.items = concatList;
          this.userList = data;
        } else {
          data.items = this.handeldefaultList(data.items);
          this.userList = data;
        }
      });
    },
    setSelectItemStyle(event) {
      const list = document.querySelectorAll('.el-select-dropdown__item');
      list.forEach(it => {
        it.style.maxWidth = 'unset!important';
      });
    },
    // 从用户列表中去除 defaultUserList 已经有的数据
    handeldefaultList(userList) {
      let res = [];
      if (userList && userList.length > 0) {
        const ids = this.defaultUserList.map(i => i.id);
        res = userList.filter(i => {
          return !ids.includes(i.id);
        });
      }
      return res;
    },
    handleSubmit() {
      this.$refs['opForm'].validate(valid => {
        if (valid) {
          this.loading = true;
          const opIds = this.formData.accountOperation.join(',');
          const res = this.cacheList.filter(it => opIds.includes(it.id));
          if (this.isCache) {
            sessionStorage.setItem('accountOperation', JSON.stringify(res));
          }
          this.$emit('submit', { opIds });
        } else {
          return false;
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.operator-dialog {
  .center{
    display: flex;
    justify-content: center;
  }
    &::v-deep {
    .el-tag.el-tag--info {
      color: #406eff;
      background: #eff3fb;
    }
  }
}
</style>
<style lang="scss">
.operator-select {
  .el-select-dropdown__item {
    max-width: unset !important;;
  }
}
</style>
